package com.wpp.mvcframemwrok.servlet;

import com.wpp.mvcframemwrok.annotation.*;
import com.wpp.mvcframemwrok.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.sun.javafx.media.PrismMediaFrameHandler.getHandler;

/**
 * @author by wpp25
 * @Classname wppDispatcherServlet
 * @Description
 * @Date 2020/10/20 22:57
 */
public class WppDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    /**
     * 缓存扫描到的类的全限定类名
     */
    private List<String> classNames = new ArrayList<>();

    /**
     * ioc 容器
     */
    private Map<String, Object> ioc = new HashMap<>();


    /**
     * 存储了 url和 某个controller 下的某个方法的映射关系
     */
    private List<Handler> handlerMappingList = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("not find 404");
            return;
        }


        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        Object[] paramValues = new Object[parameterTypes.length];
        for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) {
            // name=1 & name=2   name[1,2]
            String value = StringUtils.join(param.getValue(), ",");

            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            }

            Integer index = handler.getParamIndexMapping().get(param.getKey());
            paramValues[index] = value;
        }

        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paramValues[requestIndex] = req;

        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paramValues[responseIndex] = resp;

        if (!checkSecurity(handler,req)) {
            resp.getWriter().write("no authority access");
            return;
        }


        // 最后 调用 url对应的具体某个controller下的某个方法
        try {
            handler.getMethod().invoke(handler.getController(),paramValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private boolean checkSecurity(Handler handler,HttpServletRequest req) {
        if (handler.getClass().isAnnotationPresent(Security.class)) {
           return doCheckSecurity(req.getParameter("userName"),handler.getClass().getAnnotation(Security.class).value());
        }

        if (!handler.getMethod().isAnnotationPresent(Security.class)) {
            return true;
        }
       return doCheckSecurity(req.getParameter("userName"),handler.getMethod().getAnnotation(Security.class).value());
    }

    private boolean doCheckSecurity(String userName,String[] securityValue) {
        for (String security : securityValue) {
            if (security.equals(userName)) {
                return true;
            }
        }
        return false;
    }

    private Handler getHandler(HttpServletRequest request) {
        if (handlerMappingList.isEmpty()) {
            return null;
        }
        String requestURI = request.getRequestURI();

        for (Handler handler : handlerMappingList) {
            Matcher matcher = handler.getPattern().matcher(requestURI);
            if (!requestURI.contains(handler.getPattern().toString())) {
                continue;
            }
            /*if (!matcher.matches()) {
                continue;
            }*/
            return handler;
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 加载配置文件-- springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        // 2、扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));
        // 3、初始化bean对象（实例ioc容器，基于注解）
        doInstance();
        // 4、实现依赖注入
        doAutowired();
        // 5、构造一个HandlerMapping处理器映射器，将配置好的url和method建立映射关系
        initHandlerMapping();

        System.out.println("wpp mvc 初始化完成。。。");
        // 等待请求进入，处理请求
    }

    /**
     * 构建一个HandlerMapping处理器映射器
     * 关键点在于 将url 和 具体的某个Controller 下的某个method 关联起来
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            if (!aClass.isAnnotationPresent(WppController.class)) {
                continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(WppRequestMapping.class)) {
                baseUrl = aClass.getAnnotation(WppRequestMapping.class).value();
            }

            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(WppRequestMapping.class)){
                    continue;
                }
                String methodUrl = method.getAnnotation(WppRequestMapping.class).value();
                String url = new StringBuilder(baseUrl).append(methodUrl).toString();

                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));

                // handler 中 method 方法参数顺序的处理
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    if (parameter.getType() == HttpServletRequest.class
                            || parameter.getType() == HttpServletResponse.class) {
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),i);
                    } else {
                        handler.getParamIndexMapping().put(parameter.getName(),i);
                    }

                }
                handlerMappingList.add(handler);
            }
        }
    }

    /**
     * 注入实现
     */
    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (!declaredField.isAnnotationPresent(WppAutowired.class)) {
                    continue;
                }

                WppAutowired annotation = declaredField.getAnnotation(WppAutowired.class);
                String autowiredBeanName= annotation.value();
                if ("".equals(autowiredBeanName.trim())) {
                    autowiredBeanName = declaredField.getType().getName();
                }
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),ioc.get(autowiredBeanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * ioc 容器
     * 基于className 缓存的类的全限定类名，用反射技术 完成对象的创建和管理
     * 包括 方法入参的顺序处理
     */
    private void doInstance() {
        if (classNames.size() == 0) {
            return;
        }
        try {
            for (int i = 0; i < classNames.size(); i++) {
                // com.wpp.demo.controller.DemoController
                String className = classNames.get(i);
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(WppController.class)) {
                    // controller 取类名的首字母小写作为id 放入ioc中
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    ioc.put(lowerFirstSimpleName,aClass.newInstance());
                }

                if (aClass.isAnnotationPresent(WppService.class)) {
                    WppService annotation = aClass.getAnnotation(WppService.class);
                    String beanName = annotation.value();
                    // 如果 该注解 指定了名称 则使用其 作为id 没有则取实现类首字符小写作为id
                    if ("".equals(beanName.trim())) {
                        beanName = lowerFirst(aClass.getSimpleName());
                    }
                    ioc.put(beanName,aClass.newInstance());

                    // fixme service 层往往是有接口的，面向接口开发，此时再以接口名为id 放入一份到ioc中
                    // 以便后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        // 接口的全限定类名作为id放入
                        ioc.put(interfaces[j].getName(),aClass.newInstance());
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String lowerFirst(String simpleName) {
        char[] chars = simpleName.toCharArray();
        if (chars[0] >= 'A' && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    /**
     * scanPackage=com.wpp.demo   package ---> 磁盘上的文件
     * 扫面类
     */
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);

        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                doScan(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")){
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * 加载配置文件
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
